﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MDReader.Helper
{
    public interface IConfigurationService
    {
        string GetSetting(string key, string defaultValue = "");
        void SetSetting(string key, string value);
        void Save();
    }

    public class ConfigurationService : IConfigurationService
    {
        private readonly Dictionary<string, string> _settings;
        public ConfigurationService(ILog log)
        {
            logger = log;
            _settings = new Dictionary<string, string>();
            LoadSettings();
        }
        private readonly ILog logger;
        private void LoadSettings()
        {
            foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            {
                try
                {
                    _settings[key] = ConfigurationManager.AppSettings[key];
                } catch (Exception ex) { logger.WriteExceptionToEventLog(ex); }
            }
        }
        public string GetSetting(string key, string defaultValue = "")
        {
            try
            {
                return _settings.ContainsKey(key) ? _settings[key] : null;
            }
            catch (Exception ex) { logger.WriteExceptionToEventLog(ex); }
            return defaultValue;
        }
        public void SetSetting(string key, string value)
        {
            _settings[key] = value;
            ConfigurationManager.AppSettings[key] = value;
        }
        public void Save()
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            foreach (var key in _settings.Keys)
            {
                if (config.AppSettings.Settings[key] == null)
                {
                    config.AppSettings.Settings.Add(key, _settings[key]);
                }
                else
                {
                    config.AppSettings.Settings[key].Value = _settings[key];
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }

}
